package org.popupcommunication.controller;

import javax.validation.Valid;

import org.popupcommunication.model.AgendaPerso;
import org.popupcommunication.model.User;
import org.popupcommunication.service.AgendaPersoManager;
import org.popupcommunication.service.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("agenda/perso/")
public class AgendaPersoController {

	@Autowired AgendaPersoManager agendaPersoService;
	@Autowired UserManager userService;
	private static final String form_ajout ="agendaPerso/ajoutEvenement";
	private static final String db_ajout_confirm="agendaPerso/confirmationEvenement";
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		binder.setAllowedFields(new String[]{
		 "dateExpiration","description","titre","who"	});
	}	
	
	@RequestMapping(value="new",method = RequestMethod.GET)	
	public String showForm (Model model) {		
		model.addAttribute("agenda", new AgendaPerso());
	return form_ajout;
	}	
	
	@RequestMapping(value="/post",method = RequestMethod.POST)
	public String postForm(
			@ModelAttribute("agenda")  @Valid AgendaPerso form, BindingResult result) {
		
		//ajout database
		agendaPersoService.registerAgendaPerso(autoCompleteForm(form), result);

	return (result.hasErrors() ? form_ajout : db_ajout_confirm);
	}	
	
	private AgendaPerso autoCompleteForm(AgendaPerso ag){
		//lier le compte user à l'agenda
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		String email = auth.getName();	
			User toto = userService.findByEmail(email);
			ag.setUtilisateur(toto);
		return ag;	
	}
}
